package com.hundsun.epay.autosimu.api.dom.java;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.ListIterator;

import com.hundsun.epay.autosimu.api.dom.OutputUtility;

/**
 * 初始化块
 * @author clown
 *
 */
public class InitializationBlock {
	private boolean isStatic;   //静态
	private List<String> bodyLines;   //实现体
	private List<String> javaDocLines;   //注释
	
	public InitializationBlock() {
		this(false);
	}
	
	public InitializationBlock(boolean isStatic) {
		super();
		this.isStatic = isStatic;
		this.bodyLines = new ArrayList<String>();
		this.javaDocLines = new ArrayList<String>();
	}

	public boolean isStatic() {
		return isStatic;
	}

	public void setStatic(boolean isStatic) {
		this.isStatic = isStatic;
	}

	public List<String> getBodyLines() {
		return bodyLines;
	}

	public List<String> getJavaDocLines() {
		return javaDocLines;
	}
	
	public void addBodyLine(String line){
		this.bodyLines.add(line);
	}
	
	public void addBodyLine(int index, String line){
		this.bodyLines.add(index, line);
	}
	
	public void addBodyLines(Collection<String> lines){
		this.bodyLines.addAll(lines);
	}
	
	public void addBodyLines(int index, Collection<String> lines){
		this.bodyLines.addAll(index, lines);
	}
	
	public void addJavaDocLine(String line){
		this.javaDocLines.add(line);
	}
	
	public void addJavaDocLines(Collection<String> lines){
		this.javaDocLines.addAll(lines);
	}
	
	public String getFormattedContent(int indentLevel){
		StringBuilder sb = new StringBuilder();
		
		//注释
		for (String docLine : javaDocLines) {
			OutputUtility.javaIndent(sb, indentLevel);
			sb.append(docLine);
			OutputUtility.newLine(sb);
		}
		OutputUtility.javaIndent(sb, indentLevel);
		if(isStatic){
			sb.append("static ");
		}
		sb.append("{");
		if(!bodyLines.isEmpty()){
			indentLevel ++ ;
			ListIterator<String> listIterator = bodyLines.listIterator();
			while(listIterator.hasNext()){
				String line = listIterator.next();
				
				if(line.startsWith("}")){
					indentLevel --;
				}
				OutputUtility.newLine(sb);
				OutputUtility.javaIndent(sb, indentLevel);
				sb.append(line);
				
				if((line.endsWith("{") && !line.startsWith("switch"))
						|| line.endsWith(":")){
					indentLevel ++;
				}
				if(line.startsWith("break")){
					indentLevel --;
					if(listIterator.hasNext()){
						String nextLine = listIterator.next();
						if(nextLine.startsWith("}")){
							indentLevel ++;
						}
						listIterator.previous();
					}
				}
			}
			indentLevel --;
		}
		OutputUtility.newLine(sb);
		OutputUtility.javaIndent(sb, indentLevel);
		sb.append("}");
		return sb.toString();
	}
}
